#include "net.h"

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <strings.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>

#include "log.h"

int init_addr(struct sockaddr_in *addr,char* host,unsigned port)
{
	memset(addr,0,sizeof(struct sockaddr_in));

	if(0 == inet_aton(host,&(addr->sin_addr))) {
		perror("inet_aton");
		return -1;
	}

	addr->sin_family	= AF_INET;
	addr->sin_port		= htons(port);

	return 0;
}

int init_server_socket(struct sockaddr_in *addr)
{
	int fd;
	if (-1 == (fd = socket(AF_INET,SOCK_STREAM,0))) {
		perror("socket");
		Log(1,"%s","Cannot create socket");
		return -1;
	}

	reuse(fd);

	if(-1 == (bind(fd,(struct sockaddr*)addr,sizeof(struct sockaddr_in)))) {
		perror("bind");
		Log(1,"%s","Cannot bind socket");
		return -1;
	}

	return fd;
}

int unblock(int fd)
{
	int flags;
	if( -1 == (flags = fcntl(fd, F_GETFL, 0) ) ) {
		flags = 0;
	}

	return fcntl(fd,F_SETFL, flags | O_NONBLOCK);
}

int reuse(int fd)
{
	int value = 1;
	if(-1 == setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&value,sizeof(int))) {
		perror("setsockopt SO_REUSEADDR");
		return -1;
	}
	return 0;
}


